package com.nihome.entershopinfo.application;

import android.app.Activity;
import android.app.Application;

import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.utils.FileUtils;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * Created by Carson on 2017/7/21.
 */
public class SysApplication extends Application {
    /**  为了实现每次使用该类时不创建新的对象而创建的静态对象 */
    private static SysApplication instance;
    /** 运用list来保存们每一个activity是关键 */
    private List<Activity> AList = new LinkedList<Activity>();

    private User mUser;
    /** 全局资料ID */
    private String auditId;

    @Override
    public void onCreate() {
        super.onCreate();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    /**
     * 实例化Application
     * @return  Application
     */
    public synchronized static SysApplication getInstance() {
        if (null == instance) {
            instance = new SysApplication();
        }
        return instance;
    }

    public void addActivity(Activity activity){
        AList.add(activity);
    }

    public User getmUser() {
        try {
            if (mUser == null) {
                if (FileUtils.isFileExist(getLoginUserCacheFilePath())) {
                    StringBuilder stringBuilder = FileUtils.readFile(getLoginUserCacheFilePath(), Constants.ENCODING_RULE);
                    if (stringBuilder == null) return mUser;
                    String content = stringBuilder.toString();
                    mUser = mUser.fromJson(content);
                }
            }
        } catch (Exception ex) {
            //keep mUser as null
        }
        return mUser;
    }

    public void setmUser(User mUser) {
        this.mUser = mUser;
    }

    public String getAuditId() {
        return auditId;
    }

    public void setAuditId(String auditId) {
        this.auditId = auditId;
    }


    //app缓存文件夹
    public String getNiHomeCacheDir() {
        return Constants.CACHE_DIR;
    }
    //用户缓存路径
    public String getLoginUserCacheFilePath() {
        return getNiHomeCacheDir() + Constants.USER_CACHE_FILE_NAME;
    }

    //杀进程
    public void onLowMemory() {
        super.onLowMemory();
        System.gc();
    }


    public void exit() {
        for (Activity activity : AList) {
            if (activity != null) activity.finish();
        }
        System.exit(0);
    }
}
